package nz.ac.massey.webtech.servlets.csv;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

/**
 * Simple servlet displaying the content of a CSV file
 * as HTML table.
 * @author  Jens Dietrich   
 * @version 1.0
 */
public class CSVServlet extends HttpServlet {
    
    /** Initializes the servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
    }
    
    /** Destroys the servlet.
     */
    public void destroy() {
        
    }
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
       
        out.println("<html>");
        out.println("<head>");
        out.println("<title>CSV Servlet</title>");
        out.println("</head>");
        out.println("<body>");
        
         
        // open file
        InputStream csv = getClass().getResourceAsStream("/nz/ac/massey/webtech/servlets/csv/addresses.csv");
        BufferedReader in = new BufferedReader(new InputStreamReader(csv));
        String line = null;
        StringTokenizer tokenizer;
        
        // start table
        out.println("<h1>Converts a CSV File into an HTML Table</h1>");
        out.println("<table border>");
        
        // read line by line
        while ((line=in.readLine())!=null) {
            out.print("<tr>");
            tokenizer = new StringTokenizer(line,",");
            // read token by token
            while (tokenizer.hasMoreTokens()) {
                out.print("<td>");
                out.print(tokenizer.nextToken());
                out.print("</td>");
            }
            out.print("</tr>");
        }
        
        // finish table
        out.println("</table>");
        in.close();
        
        out.println("</body>");
        out.println("</html>");
        
        out.close();
    }
    
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    
}
